package com.discordia.asap;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AsapTakeUpload extends Activity {

	private static final int CAMERA_PIC_REQUEST = 0;

	private File photo;
	private Uri mImageUri;
	private ProgressBar pbar = null;

	static int curr_img_id = -1;
	
	
	String imgtag = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.take);
	}

	/**
	 * Called when the Camera is requested.
	 * 
	 * @param view
	 *            reference to the widget that was clicked.
	 */
	public void loadCamera(View view) {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		try {
			// place where to store camera taken picture
			photo = this.createTemporaryFile("picture", ".jpg");
			
			photo.delete();
		} catch (Exception e) {
			Toast.makeText(this,
					"Please check SD card! Image shot is impossible!", 10000);
			return;
		}
		mImageUri = Uri.fromFile(photo);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
		// start camera intent
		startActivityForResult(intent, CAMERA_PIC_REQUEST);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// If image taken update the thumbnail
		if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
			ImageView imageView;
			imageView = (ImageView) this.findViewById(R.id.imagePortrait);
			this.grabImage(imageView);
			
			//showing dialog to select image's tags
			//TODO cambiare la posizione: se apro la camera ed esco senza scattare viene mostrata lo stesso
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Tag this picture!");
			builder.setCancelable(false);
			builder.setSingleChoiceItems(AsapActivity.tagItems, -1, new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int item) {
			        //Toast.makeText(getApplicationContext(), tagItems[item], Toast.LENGTH_SHORT).show();
			        imgtag = Integer.toString(item);
			    }
			});
			builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   Toast.makeText(getApplicationContext(), "Inserted in: " + AsapActivity.tagItems[Integer.parseInt(imgtag)], Toast.LENGTH_SHORT).show();
		           }
		       });

			AlertDialog alert = builder.create();
			alert.show();
			
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	/**
	 * Create a temporary file to store an image
	 * 
	 * @param part
	 * @param ext
	 * @return
	 * @throws Exception
	 */
	private File createTemporaryFile(String part, String ext) throws Exception {
		File tempDir = Environment.getExternalStorageDirectory();
		tempDir = new File(tempDir.getAbsolutePath() + "/.temp/");
		if (!tempDir.exists()) {
			tempDir.mkdir();
		}
		return File.createTempFile(part, ext, tempDir);
	}

	/**
	 * Grab the image from the sdcard
	 * 
	 * @param imageView
	 */

	public void grabImage(ImageView imageView) {
		this.getContentResolver().notifyChange(mImageUri, null);
		ContentResolver cr = this.getContentResolver();
		Bitmap bitmap;
		try {
			bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr,
					mImageUri);
			imageView.setImageBitmap(bitmap);
		} catch (Exception e) {
			Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Called when an image upload is requested.
	 * 
	 * @param view
	 *            reference to the widget that was clicked.
	 */
	public void uploadPhoto(View view) {
		ImageUploadTask upload = new ImageUploadTask();
		pbar = (ProgressBar) findViewById(R.id.loadingBar);
		//reset progress bar
		pbar.setProgress(0);
		upload.execute(photo.getAbsolutePath());
	}

	/**
	 * Asynch task to upload an image. Takes in input an array with the image
	 * path Example:
	 * [Monstertribe.dataManager.MONSTER;Monstertribe.dataManager.ITEMS
	 * ;Monstertribe.dataManager.L_SKILLS]
	 * 
	 * @author Tia
	 * 
	 */

	public class ImageUploadTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			HttpURLConnection connection = null;
			DataOutputStream outputStream = null;

			String pathToOurFile = params[0];
			String urlServer = "http://" + AsapActivity.server
					+ AsapActivity.script_folder + "/handle_upload.php?tag="+imgtag;
			String lineEnd = "\r\n";
			String twoHyphens = "--";
			String boundary = "*****";

			String serverResponseMessage = "connection denied";

			int bytesRead, bytesAvailable, bufferSize;
			byte[] buffer;
			int maxBufferSize = 1024;

			File image = new File(pathToOurFile);
			pbar.setMax((int) (image.length() / 1024)+30);

			try {
				FileInputStream fileInputStream = new FileInputStream(image);

				URL url = new URL(urlServer);
				connection = (HttpURLConnection) url.openConnection();

				// Allow Inputs & Outputs
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setUseCaches(false);

				// Enable POST method
				connection.setRequestMethod("POST");


				connection.setRequestProperty("Connection", "Keep-Alive");
				connection.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);

				outputStream = new DataOutputStream(
						connection.getOutputStream());
				outputStream.writeBytes(twoHyphens + boundary + lineEnd);
				outputStream
						.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
								+ pathToOurFile + "\"" + lineEnd);
				outputStream.writeBytes(lineEnd);

				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];

				// Read file
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				while (bytesRead > 0) {
					outputStream.write(buffer, 0, bufferSize);
					publishProgress(new Integer(bytesRead / 1024));
					bytesAvailable = fileInputStream.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				}

				outputStream.writeBytes(lineEnd);
				outputStream.writeBytes(twoHyphens + boundary + twoHyphens
						+ lineEnd);
				//outputStream.writeBytes("tag=" + imgtag);
				// Responses from the server (code and message)
				// int serverResponseCode = connection.getResponseCode();
				serverResponseMessage = connection.getResponseMessage();

				publishProgress(30);
				
				fileInputStream.close();
				outputStream.flush();
				outputStream.close();
			} catch (Exception ex) {
				// Error TODO
			}

			/*
			 * From the php script we receive back a stream of data that has to
			 * be parsed.The string with the information we need starts with the
			 * key FEEDBACK_START and continueswith all the feedback data. Every
			 * information starts with its feedback key and it isseparated from
			 * other informations by a couple of ""TODO: define a better
			 * feedback solution to avoid the use of String.substring()
			 */
			try {
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				String line;
				while ((line = rd.readLine()) != null) {
					Log.e("Asap", "Message: " + line);
					if (line.contains("FEEDBACK_START")) {
						String feedback[] = line.split("\"\"");
						for (int k = 0; k < feedback.length; k++) {
							if (feedback[k].contains("FEEDBACK_KEY_UPLOAD"))
								serverResponseMessage = feedback[k].substring(
										19).replace("\"", "");
							else if (feedback[k].contains("FEEDBACK_KEY_ID"))
								AsapTakeUpload.curr_img_id = Integer
										.parseInt(feedback[k].substring(15));
						}
					}

				}
				rd.close();
				sendTagComment();
			} catch (IOException ioex) {
				Log.e("Asap", "error: " + ioex.getMessage(), ioex);
			}

			return serverResponseMessage;
		}

		/**
		 * Called after an image upload to send a comment and tags.
		 */
		private void sendTagComment() {
			/*try {
				String link = "http://" + AsapActivity.server
						+ AsapActivity.script_folder + "/handle_message.php";
				DefaultHttpClient hc = new DefaultHttpClient();
				HttpPost postMethod = new HttpPost(link);
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						2);
				String msg = "";

				EditText ed = (EditText) findViewById(R.id.img_msg_input);
				LinearLayout msg_lay = (LinearLayout) findViewById(R.id.msg_lay);

				// get the comment from input form and send it
				msg = ed.getText().toString();

				if (msg.isEmpty())
					// Toast.makeText(this, "Failed to send",
					// Toast.LENGTH_SHORT).show();
					throw new IOException(
							"Empty comment: please write something!");

				nameValuePairs.add(new BasicNameValuePair("tag", imgid));
				nameValuePairs.add(new BasicNameValuePair("message", msg));

				postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				BasicHttpResponse httpResponse;
				httpResponse = (BasicHttpResponse) hc.execute(postMethod);
				HttpEntity responseEntity = httpResponse.getEntity();

				/*
				 * From the php script we receive back a stream of data that has
				 * to be parsed.The string with the information we need starts
				 * with the key FEEDBACK_START and continues with all the
				 * feedback data. Every information starts with its feedback key
				 * and it is separated from other informations by a couple of ""
				 * TODO: define a better feedback solution to avoid the use of
				 * String.substring()
				 */
/*
				InputStream responseStream = responseEntity.getContent();

				BufferedReader r = new BufferedReader(new InputStreamReader(
						responseStream));

				String line;
				while ((line = r.readLine()) != null) {
					Log.e("Asap", "Message: " + line);
					if (line.contains("FEEDBACK_START")) {
						String feedback[] = line.split("\"\"");
						for (int k = 0; k < feedback.length; k++) {
							if (feedback[k].contains("FEEDBACK_KEY_MESSAGE")) {
								String fdbmessage = feedback[k].substring(20)
										.replace("\"", "");
								// toast to show the feedback message from the
								// script
								Toast.makeText(this, fdbmessage,
										Toast.LENGTH_SHORT).show();
							} else if (feedback[k]
									.contains("FEEDBACK_KEY_UPLOAD")) {
								String fdbmessage = feedback[k].substring(19)
										.replace("\"", "");
								// toast to show the feedback message from the
								// script
								Toast.makeText(this, fdbmessage,
										Toast.LENGTH_SHORT).show();
							} else if (feedback[k].contains("FEEDBACK_KEY_ID")) {
								String msgid = feedback[k].substring(15)
										.replace("\"", "");
								// msgid: id of the last message sent
							}
						}
					}
				}

				r.close();

				// hide the input form
				InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(ed.getWindowToken(), 0);
				ed.clearFocus();
				ed.setText("");
				msg_lay.setVisibility(View.GONE);

				// update messages
				getMessages(view);
			} catch (IOException ioex) {
				Toast.makeText(this, ioex.getMessage(), Toast.LENGTH_SHORT)
						.show();
				Log.e("Asap", "error: " + ioex.getMessage(), ioex);
			}*/
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		 */
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			pbar.setProgress((int) (pbar.getProgress() + values[0]));
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExectue(Result[])
		 */
		@Override
		protected void onPostExecute(String result) {
			Toast msg = Toast.makeText(getApplicationContext(), result,
					Toast.LENGTH_SHORT);
			msg.show();
		}

	}

}
